
package com.bear.cmcc.NetTestHTTP.ui.activity;

import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.ServersConfigBean;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.ui.adapter.ServerListAdapter;
import com.bear.cmcc.NetTestHTTP.ui.view.OnChangedListener;
import com.bear.cmcc.NetTestHTTP.ui.view.SlipButton;
import com.bear.cmcc.NetTestHTTP.util.NetTestUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * ���ý���
 * 
 * @author jqa
 */
public class SettingActivity extends AbstractActivity {
    private SlipButton btnAutoTest;

    private PopupWindow popupWindow;

    private TextView serverTV;

    private Button btnDown;

    // private List<ServersConfigBean> servList;
    ServerListAdapter adapter;

    ListView serverListView = null;

    List<ServersConfigBean> configList;

    Thread infoThread;

    boolean outofthread;// 判断是否已经退出获取信息线程，如果退出则不提示弹出框，避免界面view出错

    ProgressDialog myprogressDialog;

    private TextView tv2g, tvTD, tvWlan;

    private String size2g, sizeTd, sizeWlan;

    private RadioGroup periodTime;

    private RadioButton periodTime10m, periodTime30m, periodTime60m;

    private int periodValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCloseButton(R.string.top_close, buttonListener);
        setTitle(R.string.settingTitle);
        SetBottomBarVisible(false);
        setContentView(R.layout.activity_setting);
        init();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            closeWait();
            infoThread = null;

            Object obj = msg.obj;
            if (obj instanceof String) {
                String m = (String) obj;
                // if (m == "OK") {
                // Toast.makeText(SettingActivity.this, "下载成功", 0).show();
                // } else
                if (m == "ERROR") {
                    Toast.makeText(SettingActivity.this, "下载失败", 0).show();
                }
            } else {
                final ArrayList<ServersConfigBean> configList = (ArrayList<ServersConfigBean>) obj;
                if (configList != null && configList.size() > 0) {
                    popupWindowInit(configList);
                }
            }
        }
    };

    private void postMsg(Object obj) {
        Message msg = Message.obtain();
        msg.obj = obj;
        handler.sendMessage(msg);
    }

    /**
     * 根据网络类型分配下载文件大小
     */
    private void allocateFilesize() {
        int isize2g = SetUtil.getEveryDownFileSize(this, MyCommonConstant.NET_TYPE.NET_TYPE_2G);
        int isizeTd = SetUtil.getEveryDownFileSize(this, MyCommonConstant.NET_TYPE.TD);
        int isizeWlan = SetUtil.getEveryDownFileSize(this, MyCommonConstant.NET_TYPE.WLAN);
        if (isize2g < 1024) {
            size2g = isize2g + "K";
        } else {
            isize2g = isize2g / 1024;
            size2g = isize2g + "M";
        }

        if (isizeTd < 1024) {
            sizeTd = isizeTd + "K";
        } else {
            isizeTd = isizeTd / 1024;
            sizeTd = isizeTd + "M";
        }
        if (isizeWlan < 1024) {
            sizeWlan = isizeWlan + "K";
        } else {
            isizeWlan = isizeWlan / 1024;
            sizeWlan = isizeWlan + "M";
        }
    }

    /*
     * 显示等待提示框 title等待提示标题 content等待提示内容
     */
    private void showWait(String title, String content) {
        setProgressBarIndeterminateVisibility(true);
        myprogressDialog = InitProgressDialog(myprogressDialog, title, content, this);
        myprogressDialog.show();
    }

    /*
     * 关闭等待提示框
     */
    private void closeWait() {
        setProgressBarIndeterminateVisibility(false);
        if (myprogressDialog != null) {
            myprogressDialog.cancel();
            myprogressDialog = null;
        }
    }

    /**
     * 初始化组件
     */
    private void init() {
        downServerList();
        allocateFilesize();
        btnAutoTest = (SlipButton) findViewById(R.id.slipButton);
//        btnAutoTest.setChecked(true);
        initAutoButtonState();
        serverTV = (TextView) findViewById(R.id.serverAddressSpinner);
        ServersConfigBean servConf = SetUtil.getServersConfigBean(this);
        String strName = SetUtil.getServersName(this);
        serverTV.setText(strName.equals("") ? servConf.getServerName() : strName);
        btnDown = (Button) findViewById(R.id.serverAddressDown);
        tv2g = (TextView) findViewById(R.id.textView2g);
        tvTD = (TextView) findViewById(R.id.textViewTd);
        tvWlan = (TextView) findViewById(R.id.textViewWlan);
        tv2g.setText(tv2g.getText().toString() + size2g);
        tvTD.setText(tvTD.getText().toString() + sizeTd);
        tvWlan.setText(tvWlan.getText().toString() + sizeWlan);
        btnDown.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showWait("", "下载中...");
//                updateServerConfig();
                downServerList();
            }
        });
        // servList = SetUtil.getServersConfigs(this);
        periodTime = (RadioGroup) findViewById(R.id.periodTime);
        periodTime10m = (RadioButton) findViewById(R.id.periodTime10m);
        periodTime10m.setChecked(true);
        periodTime30m = (RadioButton) findViewById(R.id.periodTime30m);
        periodTime60m = (RadioButton) findViewById(R.id.periodTime60m);
        periodTime.setOnCheckedChangeListener(periodTimeSelectListener);
        initPeriodButtonState();
        btnAutoTest.SetOnChangedListener(new OnChangedListener() {

            @Override
            public void OnChanged(boolean CheckState) {
                // TODO Auto-generated method stub
                SetUtil.setAutoTest(SettingActivity.this, CheckState);
                if (CheckState) {
                    NetTestUtil.startAutoNetTestService(SettingActivity.this);
                    Toast.makeText(getBaseContext(), getString(R.string.openautotest),
                            Toast.LENGTH_SHORT).show();
                } else {
                    NetTestUtil.stopAutoNetTestService(SettingActivity.this);
                    Toast.makeText(getBaseContext(), getString(R.string.closeautotest),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initAutoButtonState() {
        boolean flag = SetUtil.getAutoTest(this);
        if (flag) {
            btnAutoTest.setChecked(true);
        } else {
            btnAutoTest.setChecked(false);
        }
    }

    private void initPeriodButtonState() {
        periodValue = SetUtil.getAutoTestGap(this);
        if (10 == periodValue) {
            periodTime10m.setChecked(true);
        } else if (30 == periodValue) {
            periodTime30m.setChecked(true);
        } else if (60 == periodValue) {
            periodTime60m.setChecked(true);
        }

    }

    private OnCheckedChangeListener periodTimeSelectListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // TODO Auto-generated method stub
            switch (checkedId) {
                case R.id.periodTime10m:
                    if (SetUtil.setAutoTestGap(SettingActivity.this, 10)) {
                        NetTestUtil.restartAutoNetTestService(SettingActivity.this);
                    }
                    break;
                case R.id.periodTime30m:
                    if (SetUtil.setAutoTestGap(SettingActivity.this, 30)) {
                        NetTestUtil.restartAutoNetTestService(SettingActivity.this);
                    }
                    break;
                case R.id.periodTime60m:
                    if (SetUtil.setAutoTestGap(SettingActivity.this, 60)) {
                        NetTestUtil.restartAutoNetTestService(SettingActivity.this);
                    }
                    break;
                default:
                    break;
            }
        }
    };

//    /**
//     * 更新服务器列表
//     */
//    private void updateServerConfig() {
//        infoThread = new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//                boolean success = SetUtil.updateServiceConfig(SettingActivity.this);
//                if (success) {
//                    downServerList();
//                } else {
//                    postMsg("ERROR");
//                }
//            }
//        });
//        infoThread.start();
//    }

    /**
     * 下载服务器列表
     */
    private void downServerList() {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                ArrayList<ServersConfigBean> servList = SetUtil.getServersConfigsAdapter(SettingActivity.this);
                if (servList != null && servList.size() > 0) {
                    postMsg(servList);
                }else if(servList==null)
                {
                    postMsg("ERROR");
                }else
                {
                    postMsg("no");
                }
            }
        });
        t.start();
    }

    /**
     * 初始化popwin
     * 
     * @param _servList
     */
    private void popupWindowInit(final List<ServersConfigBean> _servList) {
        adapter = new ServerListAdapter(this, _servList);
        serverListView = (ListView) LayoutInflater.from(this).inflate(R.layout.layout_popuserver,
                null);
        serverListView.setAdapter(adapter);
        LayoutParams lp = serverTV.getLayoutParams();
        popupWindow = new PopupWindow(serverListView, lp.width, LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        serverListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                ServersConfigBean serconf = _servList.get(arg2);
                serverTV.setText(serconf.getServerName());
                SetUtil.setServersConfigBean(serconf, SettingActivity.this);
                popupWindow.dismiss();
            }
        });
        serverTV.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showPopupWidow(v);
            }
        });
    }

    /**
     * 弹窗
     * 
     * @param v
     */
    private void showPopupWidow(View v) {
        popupWindow.showAsDropDown(v);
    }

    private OnClickListener buttonListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    };

    /**
     * 初始化等待提示框
     */
    private ProgressDialog InitProgressDialog(ProgressDialog myprogressDialog, String title,
            String message, Activity ac) {
        myprogressDialog = new ProgressDialog(ac);

        myprogressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        myprogressDialog.setTitle(title);

        myprogressDialog.setMessage(message);

        myprogressDialog.setIndeterminate(false);
        return myprogressDialog;
    }
}
